package com.zhj.rpc05;

import com.zhj.common.entity.User;
import com.zhj.common.service.IUserService;

import java.io.*;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhj
 */
public class Server {

    private static boolean runing = true;

    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(8888);
        while (runing) {
            Socket s = ss.accept();
            process(s);
            s.close();
        }
        ss.close();
    }

    /**
     * 处理过程
     * @param s
     * @throws Exception
     */
    private static void process(Socket s) throws Exception {
        InputStream in = s.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(in);
        OutputStream out = s.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);

        String methodName = ois.readUTF();
        Class[] parameterTypes = (Class[]) ois.readObject();
        Object[] args = (Object[]) ois.readObject();

        IUserService service = new UserServiceImpl();
        Method method = service.getClass().getMethod(methodName, parameterTypes);
        User user = (User) method.invoke(service, args);

        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(user);
        oos.flush();
    }

}
